package com.lottery.ruok.lottrey.chat.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.android.lib.dialog.BottomDialog;
import com.android.lib.dialog.Builder;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.BaseActivity;
import com.lottery.ruok.lottrey.activity.NewChannelInfoActivity;
import com.lottery.ruok.lottrey.adapter.MyConversationListAdapter;
import com.lottery.ruok.lottrey.adapter.PrizePeopleAdapter;
import com.lottery.ruok.lottrey.bean.OrderObservableList;
import com.lottery.ruok.lottrey.chat.RongCloudChatActivityHelper;
import com.lottery.ruok.lottrey.chat.base.BaseChatActivity;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRongUserInfoRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRongUserInfoReponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomUsersResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import ui.NavigateBar;
import utils.Utils;

/**
 * 作者：lm
 * <p>
 * 创建日期：2018/9/14$
 * <p>
 * 描述：聊天记录页面
 */
public class MyConversationListActivity extends BaseActivity {
    @BindView(R.id.navigateBar)
    NavigateBar navigateBar;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.no_net_view)
    LinearLayout no_net_view;
    private List<Conversation> conversationsList = new ArrayList<>();
    Handler myHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    setConversationRecord();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private List<GetRoomUsersResponse.ListBean> listBeans = new ArrayList<>();
    private MyConversationListAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        initView();
        load();
    }


    protected void init() {
        setContentView(R.layout.activity_conversation_list_my);
        ButterKnife.bind(this);
    }


    protected void initView() {
       /* swipeRefreshLayout.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                getList(mIndex);
                return true;
            }

            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                getList(0);
            }
        });*/
        list.setLayoutManager(new LinearLayoutManager(this));
        list.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new MyConversationListAdapter(MyConversationListActivity.this, listBeans);
        list.setAdapter(adapter);
        adapter.setChangLongListener(new MyConversationListAdapter.MyConversationLisListener() {
            @Override
            public void ChangLongClick(int posion, int tag) {
                GetRoomUsersResponse.ListBean bean = listBeans.get(posion);
                switch (tag) {
                    case 1:

                        if (posion < listBeans.size()) {
                            setSelect(bean, posion);
                        }


                        break;
                    case 2:
                        if (UserInfo.getMyUserId().equals(bean.getRy_id())) {
                            Utils.showToast("这是本人，不能和自己聊天");
                            return;
                        }
                        RongCloudChatActivityHelper.startPrivateChat(MyConversationListActivity.this, bean.getRy_id(), bean.getNickname());

                        break;
                }
            }
        });
    }

    private void setSelect(final GetRoomUsersResponse.ListBean bean, final int posion) {
        Builder builder = new Builder(MyConversationListActivity.this);//首先自己不能和自己聊天，已经是管理员的人不能再被设为管理员，自己也不能移除自己
        builder.addOption("私聊", Color.parseColor("#007aff"), new BottomDialog.OnOptionClickListener() {
            @Override
            public void onOptionClick() {
                RongCloudChatActivityHelper.startPrivateChat(MyConversationListActivity.this, bean.getRy_id(), bean.getNickname());
            }
        });

        builder.addOption("删除记录", Color.parseColor("#007aff"), new BottomDialog.OnOptionClickListener() {
            @Override
            public void onOptionClick() {
                RongIM.getInstance().removeConversation(Conversation.ConversationType.PRIVATE, bean.getRy_id(), new RongIMClient.ResultCallback<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        listBeans.remove(posion);
                        if (adapter!=null){
                            adapter.notifyDataSetChanged();
                        }
                        if (listBeans.size()==0){
                            no_net_view.setVisibility(View.VISIBLE);
                        }

                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }
        });
        builder.create().show();

    }

    private void getList() {
        RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                conversationsList.clear();
                if (conversations != null&&conversations.size()>0) {

                        conversationsList.addAll(conversations);
                        //县城进程啊
                        android.os.Message nessage = new android.os.Message();
                        nessage.what = 1;
                        myHandler.sendMessage(nessage);
                    no_net_view.setVisibility(View.GONE);
                    }else {
                    no_net_view.setVisibility(View.VISIBLE);
                    }

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        }, Conversation.ConversationType.PRIVATE);
    }


    protected void load() {
        getList();
       /* RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                conversationsList.clear();
                if (conversations != null) {
                    conversationsList.addAll(conversations);
                }
                //县城进程啊
                android.os.Message nessage = new android.os.Message();
                nessage.what = 1;
                myHandler.sendMessage(nessage);

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        }, Conversation.ConversationType.PRIVATE);*/
    }

    private void setConversationRecord() {

        String rongId = "";
        if (conversationsList.size() > 0) {

            for (int i = 0; i < conversationsList.size(); i++) {
                Conversation conversationBean = conversationsList.get(i);
                if (i == 0) {
                    rongId = conversationsList.get(i).getTargetId();
                } else {
                    rongId = rongId + "," + conversationsList.get(i).getTargetId();
                }
            }

            RetrofitBase.getRetrofit().create(GetRongUserInfoRequest.class).getResult(null, null, rongId)
                    .compose(RxHelper.<GetRongUserInfoReponse>handleResult())
                    .subscribe(new RxSubscribe<GetRongUserInfoReponse>(this) {
                        @Override
                        protected void _onNext(GetRongUserInfoReponse getRongUserInfoReponses) {

                            if (getRongUserInfoReponses != null) {

                                for (int i = 0; i < getRongUserInfoReponses.getList().size(); i++) {
                                    GetRongUserInfoReponse.ListBean bean = getRongUserInfoReponses.getList().get(i);
                                    GetRoomUsersResponse.ListBean listBean = new GetRoomUsersResponse.ListBean();

                                    listBean.setChatroom_role(bean.getChatroom_role());
                                    listBean.setDataType(1);
                                    listBean.setNickname(bean.getNickname());
                                    listBean.setAvatar(bean.getAvatar());
                                    listBean.setRy_id(bean.getRy_id());
                                    listBean.setOnline_status(bean.getOnline_status());
                                    listBeans.add(listBean);


                                }

                                adapter.notifyDataSetChanged();
                            }


                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                        }

                        @Override
                        protected boolean showDialog() {
                            return true;
                        }
                    });


        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter!=null){
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
